package service

import (
	"server_cluster/common/logger"
	"server_cluster/http/model"
	"server_cluster/http/pkg/random"
	"strconv"

	"slices"
	"sort"
)

// RandomGetGateServer 随机获取网关服务器
func (s *Service) RandomGetGateServer() (*model.DbServer, error) {
	serverList, err := s.d.GetServerListByType(model.ServerTypeGate)
	if err != nil {
		return nil, err
	}
	serverList = slices.DeleteFunc[[]*model.DbServer, *model.DbServer](serverList, func(server *model.DbServer) bool {
		return server.Status == 0 || server.Stock == 0
	})
	if len(serverList) == 0 {
		return nil, nil
	}
	sort.Slice(serverList, func(i, j int) bool {
		return serverList[i].Stock > serverList[j].Stock
	})
	maxStock := serverList[0].Stock
	serverList = slices.DeleteFunc[[]*model.DbServer, *model.DbServer](serverList, func(server *model.DbServer) bool {
		return server.Stock != maxStock
	})
	rn := random.GetRandomInt32(0, int32(len(serverList)-1))
	server := serverList[rn]
	return server, nil
}

func (s *Service) GetAllGateServer() ([]*model.Region, error) {
	serverList, err := s.d.GetActiveServerListByType(model.ServerTypeGate)
	if err != nil {
		logger.Error("get serverListByType err:", err)
		return nil, err
	}
	var servers []*model.Region
	for _, server := range serverList {
		servers = append(servers, &model.Region{
			Addr:  server.Ip + ":" + strconv.Itoa(int(server.Port)),
			Title: server.Name,
			Stock: server.Stock,
		})
	}
	return servers, nil
}

func (s *Service) RefreshAccountRegisterCount() error {
	registerCount, err := s.d.GetAccountRegisterCount()
	if err != nil {
		logger.Error("get accountRegisterCount err:", err)
		return err
	}
	s.PlayerCount = registerCount
	return nil
}

func (s *Service) SetServerStartTime() {
	s.ServerStartTime, _ = s.d.GetServerStartTime()
}
